package com.example.lib_db.db.room

import android.content.Context
import androidx.room.AutoMigration
import androidx.room.Room
import androidx.room.migration.AutoMigrationSpec
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
import com.baway.db.AppDataBase
import com.example.lib_db.db.room.migrations.UserInfoColumnDeleteMigration
import com.example.lib_db.db.room.migrations.UserInfoColumnNameMigration

/**
 * Room数据工具类
 */
object RoomDBUtils {
    private const val parkDataBaseName ="smart_park_db"
    private lateinit var roomDb:AppDataBase

    private val MIGRATION_1_2 =object :Migration(1,2){
        override fun migrate(database: SupportSQLiteDatabase) {
            try {//使用SQL语句来升级数据库
                val renameTableSQL = "'ALTER TABLE user_info_table RENAME TO user_info"
                database.execSQL(renameTableSQL)
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }
    //自动升级策略
    private val AUTOMIGRATION_SPEC = object :AutoMigrationSpec{
        override fun onPostMigrate(db: SupportSQLiteDatabase) {
            super.onPostMigrate(db)
            try {//使用SQL语句来升级数据库
                val renameTableSQL = "'ALTER TABLE user_info_table RENAME TO user_info"
                db.execSQL(renameTableSQL)
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }
    /**
     * 初始化
     */
    fun initRoom(ctx:Context){
        roomDb=Room.databaseBuilder(ctx,AppDataBase::class.java, parkDataBaseName)
            //  .addAutoMigrationSpec(UserInfoColumnNameMigration())
            //.addMigrations(MIGRATION_1_2)
            //.addAutoMigrationSpec(AUTOMIGRATION_SPEC)
            .build()
    }
}